function padHex(value: number): string {
  return value.toString(16).padStart(2, '0').toUpperCase();
}

export function repeatDaysToByte(days: number[]): number {
  return days.reduce((acc, day) => {
    if (day >= 1 && day <= 7) {
      return acc | (1 << (day - 1)); // 周一是 bit0
    }
    return acc;
  }, 0);
}

export function repeatDaysToHex(days: number[]): string {
  const byte = repeatDaysToByte(days);
  return  byte.toString(16).padStart(2, '0');
}

/**
 * 生成定时
 */
export function generateTimingRaw(isOn: boolean, hour: number): string {
  const switchByte = isOn ? 1 : 0;
  return [padHex(switchByte), padHex(hour)].join('');
}

/**
 * 生成区间透传
 * @param isOn 是否开启（true 开 / false 关）
 * @param startHour 开始小时 (0-23)
 * @param startMinute 开始分钟 (0-60)
 * @param endHour 结束小时 (0-23)
 * @param endMinute 结束分钟 (0-60)
 * @returns Hex 指令字符串
 */
export function generateSectionRaw(
  isOn: boolean,
  startHour: number,
  startMinute: number,
  endHour: number,
  endMinute: number
): string {
  const switchByte = isOn ? 1 : 0;
  return [
    padHex(switchByte),
    padHex(startHour),
    padHex(startMinute),
    padHex(endHour),
    padHex(endMinute),
  ].join('');
}

/**
 * 生成档位透传
 */
export function generateGearRaw(isOn: boolean, gear: number): string {
  const switchByte = isOn ? 1 : 0;
  return [padHex(switchByte), padHex(gear)].join('');
}

/**
 * 生产周期透传
 * @param days
 * @returns
 */
export function generateCycleRaw(isOn: boolean, days: number[]): string {
  const switchByte = isOn ? 1 : 0;
  const repeatBits = repeatDaysToHex(days);
  return [padHex(switchByte), repeatBits].join('');
}

/**
 * 生产场景透传
当前选择的场景：0：未选择  1-11 场景枚举
场景一：0: 自定义  1-11场景枚举
场景二：0: 自定义  1-11场景枚举
场景三：0: 自定义  1-11场景枚举
场景四：0: 自定义  1-11场景枚举
 */
export function generateSceneRaw(
  currentScene: number,
  scene1: number,
  scene2: number,
  scene3: number,
  scene4: number
): string {
  const switchByte = currentScene;
  return [padHex(switchByte), padHex(scene1), padHex(scene2), padHex(scene3), padHex(scene4)].join(
    ''
  );
}

/**
 * 生成Work透传
 */
export function generateWorkRaw(
  gear: number,
  startHour: number,
  startMinute: number,
  endHour: number,
  endMinute: number,
  days: number[]
): string {
  const repeatByte = repeatDaysToHex(days);
  return [
    padHex(gear),
    padHex(startHour),
    padHex(startMinute),
    padHex(endHour),
    padHex(endMinute),
    repeatByte,
  ].join('');
}
